package com.wx.commons.annotation;

import com.wx.commons.annotation.Check;
import com.wx.commons.constant.CheckValidatorEnum;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Component
@Configuration
public class CheckValidator implements ConstraintValidator<Check, Object> {

    private Check check;
    private CheckValidatorEnum checkValidatorEnum;

    @Override
    public void initialize(Check CheckAnnotation) {
        this.check = CheckAnnotation;
        this.checkValidatorEnum = CheckAnnotation.type();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {

        if (checkValidatorEnum.getCode() == CheckValidatorEnum.Null.getCode()) {
            //非空校验
            if (o != null && !o.toString().equals("")) {
                return true;
            }
        } else if (checkValidatorEnum.getCode() == CheckValidatorEnum.AGE.getCode()) {
            //年龄校验
            if (o.toString() == null) {
                return true;
            }
            long min = this.check.min();
            long max = this.check.max();
            Integer age = Integer.parseInt(o.toString());
            if (age >= min && age <= max) {
                return true;
            }
        } else if (checkValidatorEnum.getCode() == CheckValidatorEnum.Phone.getCode()) {
            if (o == null) {
                return true;
            }
            //手机号码校验
            if (o.toString().length() == 11) {
                return true;
            }
        }
        return false;
    }
}


